/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package servlet;

import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import persistencia.*;

/**
 *
 * @author pabloavila
 */
@WebServlet(name="Controller", urlPatterns={"/login", "/logout", "/doPost", "/doAddUser", "/doEditUser", "/doRemoveUser"})
public class Controller extends HttpServlet {

    @EJB
    private PermisosFacade permisosFacade;
    private UsuariosFacade usuariosFacade;
    private MensajesFacade mensajesFacade;

    @Override
    public void init(){

        // Elementos a inicializar con el servlet

        // Intentamos crear los permisos
       try{
        permisosFacade.create(new Permisos("GUEST"));
        permisosFacade.create(new Permisos("USER"));
        permisosFacade.create(new Permisos("ADMIN"));

        // Creamos el usuario admin por defecto
        usuariosFacade.create(new Usuarios("admin","ADMIN"));

        // Cramos un mensaje a mostrar por defecto
        mensajesFacade.create(new Mensajes("Este es un mensaje de Bienvenida!!", "admin"));
        }
       catch (Exception e){
           // Mostrar la excepcion
       }
    }
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String userPath = request.getServletPath();

        HttpSession session = request.getSession(false);

        // Si hace login
        if (userPath.equals("/login")) {
            // Miramos en la BD que existe el usuario
            String formname = request.getParameter("name");
            String formpermission = request.getParameter("usertype");
            Usuarios u = usuariosFacade.getUsuario(formname, formpermission);

            // Si existe, iniciamos sesion
            if (u != null){
                session.setAttribute("user",u);
                session.setAttribute("error",false);
                session.setAttribute("msg","Bienvenido " + u.getNombre());
            }            
            // Si no existe, mostramos mensaje de error
            else{
                session.setAttribute("user",null);
                session.setAttribute("error",true);
                session.setAttribute("msg","El usuario " + formname + " no existe o no tiene los suficientes permisos");
            }

        // if cart page is requested
        } else if (userPath.equals("/logout")) {
            // TODO: Implement cart page request

            userPath = "/cart";

        // if checkout page is requested
        } else if (userPath.equals("/doPost")) {
            // TODO: Implement checkout page request

        // if user switches language
        } else if (userPath.equals("/doAddUser")) {
            // TODO: Implement language request

        } else if (userPath.equals("/doEditUser")) {
            // TODO: Implement language request


        } else if (userPath.equals("/doRemoveUser")) {
            // TODO: Implement language request

        }

        // use RequestDispatcher to forward request internally
        String url = "/WEB-INF/view" + userPath + ".jsp";

        try {
            // Reenviamos
            request.getRequestDispatcher(url).forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
